<!--
 * @FilePath: /web-vue/src/views/HousingOrder/addForm.vue
 * @Description: 【租房订单】新增表单
-->
<template>
  <div>
    <!-- 弹出层-表单 -->
    <el-dialog
      class="add-dialog"
      title="新增【租房订单】"
      :visible.sync="visible"
      :confirmLoading="confirmLoading"
      top="7vh"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      :fullscreen="false"
    >
      <el-form
        :model="addForm"
        :rules="rules"
        ref="addForm"
        status-icon
        label-width="150px"
        style="width: 100%"
        class="layer-form-style"
      >
        <el-form-item label="房源ID：" prop="houseId" size="mini">
          <el-input
            v-model="addForm.houseId"
            readOnly
            style="width: 99%"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="预定入住日期："
          prop="orderStartTimeRange"
          size="mini"
        >
          <el-date-picker
            v-model="addForm.orderStartTimeRange"
            type="datetimerange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['8:00:00', '22:00:00']"
            :picker-options="DateTimeRange_Picker_Option"
            @change="dateSelectChange()"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否需要餐饮：" prop="isNeedMeal" size="mini">
          <el-radio-group v-model="addForm.isNeedMeal">
            <el-radio
              v-for="item in $store.state.DICT.isNeedMealSelect"
              :key="item.code"
              :label="item.code"
              >{{ item.name }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="addForm.isNeedMeal === '1'">
          <el-button
            type="success"
            icon="el-icon-hot-water"
            @click="chooseMeal()"
            >选择餐饮
          </el-button>
        </el-form-item>
        <el-form-item
          v-if="addForm.isNeedMeal === '1'"
          label="餐饮ID："
          size="mini"
        >
          <el-input
            v-model="addForm.mealId"
            readOnly
            style="width: 99%"
          ></el-input>
        </el-form-item>
        <el-form-item
          v-if="addForm.isNeedMeal === '1'"
          label="餐饮示例图："
          size="mini"
        >
          <el-image
            v-if="mealImageUrl"
            style="width: 100px; height: 100px"
            :src="`${$store.state.API_ROOT}${mealImageUrl}`"
          >
          </el-image>
        </el-form-item>
        <el-form-item label="入住天数：" prop="housingDay" size="mini">
          <el-input
            v-model="tempObj.housingDay"
            readOnly
            style="width: 99%"
          ></el-input>
        </el-form-item>
        <el-form-item label="折扣：" prop="discount" size="mini">
          <el-input-number
            v-model="tempObj.discount"
            disabled
          ></el-input-number>
        </el-form-item>
        <el-form-item label="房费：" prop="houseCost" size="mini">
          <el-input-number
            v-model="tempObj.houseCost"
            disabled
          ></el-input-number>
        </el-form-item>
        <el-form-item
          v-if="addForm.isNeedMeal === '1'"
          label="餐饮费："
          prop="mealCost"
          size="mini"
        >
          <el-input-number
            v-model="tempObj.mealCost"
            disabled
          ></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-tag type="danger">预估总费用：</el-tag>
          <el-link style="font-size: 30px" type="danger" :underline="false"
            >￥ {{ tempObj.totalCost }}</el-link
          >
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          icon="el-icon-finished"
          @click="handleSubmit()"
          >提交订单
        </el-button>
        <el-button icon="el-icon-refresh-left" @click="handleCancel()"
          >取消
        </el-button>
      </div>
    </el-dialog>
    <!-- 餐饮选择弹窗 -->
    <el-dialog
      title="餐饮供应表"
      :visible.sync="visible2"
      top="7vh"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      :fullscreen="true"
    >
      <MealIndex
        ref="mealIndex"
        :isShowAdminBtn="false"
        @afterSelect="afterChooseMeal"
      ></MealIndex>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="success"
          icon="el-icon-finished"
          @click="
            () => {
              visible2 = false;
              afterChooseMeal(mealObj);
            }
          "
          >保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import MealIndex from "../Meals/index";

import {
  DateTimeRange_Picker_Option,
  DateRange_Picker_Option,
  Date_Picker_Option,
} from "@/utils/datePicker";

export default {
  components: {
    MealIndex,
  },

  data() {
    return {
      visible: false,
      confirmLoading: false,
      addForm: {
        houseId: null,
        mealId: null,
        isNeedMeal: null,
        orderStartTime: null,
        orderEndTime: null,
        // 辅助属性
        orderStartTimeRange: null,
      },
      tempObj: {
        housingDay: 0, // 天数
        cost: 0, // 房费单价
        mealPrice: 0, // 餐饮费单价
        houseCost: 0, // 房费
        mealCost: 0, // 餐饮费
        totalCost: 0, // 总费用
        discount: 0, // 折扣
      },
      // 表单校验规则
      rules: {
        // houseId: [
        //   {
        //     required: true,
        //     message: "房源ID不能为空！",
        //     trigger: "blur",
        //   },
        // ],
        isNeedMeal: [
          {
            required: true,
            message: "是否需要餐饮不能为空！",
            trigger: "blur",
          },
        ],
        orderStartTimeRange: [
          {
            required: true,
            message: "预定入住日期不能为空！",
            trigger: "blur",
          },
        ],
      },
      // 日期选择快捷方式
      DateTimeRange_Picker_Option,
      DateRange_Picker_Option,
      Date_Picker_Option,
      mealImageUrl: null,
      visible2: false,
      mealObj: null,
    };
  },

  computed: {
    // 天数
    housingDay() {
      return this.tempObj.housingDay;
    },
    // 餐饮单价
    mealPrice() {
      return this.tempObj.mealPrice;
    },
    // 是否需要餐饮
    isNeedMeal() {
      return this.addForm.isNeedMeal;
    },
  },

  // 监听属性变化，配合 computed
  watch: {
    // 天数
    housingDay(newVal, oldVal) {
      // 计算房费
      this.tempObj.houseCost =
        this.tempObj.cost * this.tempObj.discount * newVal;
      // 计算餐饮费
      this.tempObj.mealCost = this.tempObj.mealPrice * newVal;
      // 计算总费用
      this.tempObj.totalCost = parseFloat(
        (this.tempObj.houseCost + this.tempObj.mealCost).toPrecision(12)
      );
    },
    // 餐饮单价
    mealPrice(newVal, oldVal) {
      // 计算餐饮费
      this.tempObj.mealCost = newVal * this.tempObj.housingDay;
      // 计算总费用
      this.tempObj.totalCost = parseFloat(
        (this.tempObj.houseCost + this.tempObj.mealCost).toPrecision(12)
      );
    },
    // 是否需要餐饮
    isNeedMeal(newVal, oldVal) {
      if (newVal !== "1") {
        this.tempObj.mealPrice = 0;
        this.addForm.mealId = null;
        this.mealImageUrl = null;
      }
    },
  },

  methods: {
    // 打开【租房订单】表单新增窗口
    openAddForm(isShow, item) {
      // 检查登录状态
      if (this.$store.state.userSession) {
        this.visible = isShow;
        if (item) {
          this.addForm.houseId = item.id;
          this.tempObj.cost = item.cost;
          this.tempObj.discount = item.discount;
        }
      } else {
        this.$router.push({
          name: "login",
          query: { redirect: `/Housing/detail/${item.id}` },
        });
      }
    },

    // 关闭【租房订单】表单新增窗口
    handleCancel() {
      this.visible = false;
      this.$refs["addForm"].resetFields();

      // 清空上传文件列表
    },

    // 提交
    handleSubmit() {
      this.$refs["addForm"].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            target: document.querySelector(".add-dialog"),
            lock: true,
            text: "正在保存，请耐心等待！",
          });

          // 请求参数
          let param = Object.assign({}, this.addForm);

          if (this.addForm.orderStartTimeRange) {
            param["orderStartTime"] = this.addForm.orderStartTimeRange[0];
            param["orderEndTime"] = this.addForm.orderStartTimeRange[1];
          }

          delete param.orderStartTimeRange;

          // 发起请求
          this.$api
            .addHousingOrder(param)
            .then((res) => {
              loading.close();
              let { status, message, data } = res.data; // 响应数据
              if (status == 200) {
                this.$emit("afterSubmit");
                this.handleCancel();
                // 提示信息
                this.$message({
                  type: "success",
                  message: `操作成功！已新增【租房订单】!${message}`,
                  duration: 1680,
                });
              } else if (status == 403) {
                this.$message({
                  message: `权限不足！${message}`,
                  type: "error",
                  center: true,
                  duration: 1680,
                });
                // this.$router.push("/login");
              } else {
                this.$alert(`操作失败！${message}`, "【租房订单】新增", {
                  type: "error",
                  confirmButtonText: "确定",
                  callback: (action) => {},
                });
              }
            })
            .catch((err) => {
              loading.close();
              this.visible = false;
              console.log(`【租房订单】新增接口发生错误：${err}`);
            });
        }
      });
    },

    // 日期选择变化
    dateSelectChange() {
      const diff = this.$moment(this.addForm.orderStartTimeRange[1]).diff(
        this.addForm.orderStartTimeRange[0]
      );
      // 计算天数
      this.tempObj.housingDay = Math.ceil(diff / (3600 * 1000 * 24));
    },

    // 选择餐饮
    chooseMeal() {
      this.visible2 = true;
      setTimeout(() => {
        this.$refs.mealIndex.queryDataBtn();
      }, 9);
    },

    // 选择餐饮后回调
    afterChooseMeal(item) {
      if (item) {
        this.mealObj = item;
        // 其他参数赋值
        this.addForm.mealId = item.id;
        this.mealImageUrl = item.mealImageUrl;
        this.tempObj.mealPrice = item.price;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
// 表单布局样式
@import "@/assets/css/form-layout.scss";
</style>
